const fs = require("fs")
const sql = require("sql.js")
const myinfo = require("./myinfo")
module.exports = {
    db: null,
    //创建一个数据库
    createDB: function(falg){
        if(falg){
            this.db = new sql.Database(fs.readFileSync("./sqlite/"+myinfo.my.account+".sqlite"))
        }else{
            this.db = new sql.Database()
            this.db.run(`CREATE TABLE session (
            "id"  INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
            "name"  TEXT,
            "text"  TEXT,
            "contentJson"  TEXT );`)
            this.writeSqlite();
        }
    },
    //将数据写入由IM账号命名的数据库
    writeSqlite:function(){
        var data = this.db.export()
        var buffer = new Buffer(data)
        fs.writeFileSync("./sqlite/"+myinfo.my.account+".sqlite",buffer)
    },
    //存储onMsg信息
    writeToOnMsg: function(msg){
        return this.ifTableInDb(msg)
    },
    //判断数据库中表是否存在
    ifTableInDb: function(msg){
        console.log(msg)
        const tableName = msg.scene+msg.target;
        const contentJson = JSON.stringify(msg)
        const table = this.db.exec(`select count(*)  from sqlite_master where type='table' and name = '${tableName}'`)[0].values
        let sqlstr =table[0][0] > 0 ? `` : `CREATE TABLE ${tableName} (
            "id"  INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
            "type"  TEXT,
            "text"  TEXT,
            "target"  TEXT,
            "contentJson"  TEXT,
            "time"  INTEGER);`
         sqlstr+= `INSERT INTO ${tableName} (type,text,target,contentJson,time) VALUES 
            ('${msg.type}','${msg.text}','${msg.scene+msg.target}','${contentJson}','${msg.time}');`
         //聊天记录
         this.db.run(sqlstr)
         //最近会话列表
         this.db.run(`DELETE FROM session where name='${msg.scene+msg.target}';`)
         this.db.run(`INSERT INTO session (name,text,contentJson) values 
        ('${msg.scene+msg.target}','${msg.text}','${contentJson}');`)
         this.writeSqlite();
        return msg
    }
}